<?php

?>

<div class="layui-fluid layui-anim layui-anim-fadein layui-col-md-offset1 layui-col-md10">
    <div class="layui-card">
        <div class="layui-card-header">
            <b>Pchat</b>
        </div>
        <div class="layui-card-body">
            <form class="layui-form" action="" method="post">
                <div class="layui-form-item">
                    <label class="layui-form-label">发送内容</label>
                    <div class="layui-input-block">
                        <textarea class="layui-textarea" name="content"></textarea>
                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <div class="layui-block">
                            <button class="layui-btn layui-btn-normal layui-btn-sm" lay-submit
                                    lay-filter="submit">发送
                            </button>
                        </div>
                    </div>
                </div>
            </form>

            <div class="layui-card-body" id="chat_panel">
            </div>
        </div>
    </div>
</div>


<?php $this->beginBlock('js') ?>
<script>
    var wsServer = 'ws://106.53.223.109:39501?access_token=<?= Yii::$app->user->identity->accessToken?>';
    var websocket = new WebSocket(wsServer);
    websocket.onopen = function (evt) {
        // console.log("Connected to WebSocket server.");
    };

    websocket.onclose = function (evt) {
        // console.log("Disconnected");
    };

    websocket.onmessage = function (evt) {
        console.log(evt.data);
        $('#chat_panel').append("<p>" + evt.data + "</p>");
    };

    websocket.onerror = function (evt, e) {
        // console.log('Error occured: ' + evt.data);
    };

    //监听提交
    layui.form.on('submit(submit)', function (data) {
        websocket.send(data.field.content)
        return false;
    });
</script>
<?php $this->endBlock() ?>
